package com.tfswue.hql.service;

import com.tfswue.hql.entity.User;
import com.tfswue.hql.exception.BusinessException;
import com.tfswue.hql.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    public User getUserById(Long id) {
        try {
            return userMapper.selectById(id);
        } catch (Exception e) {
            log.error("查询用户失败，用户ID: {}", id, e);
            throw new BusinessException("查询用户失败");
        }
    }
    
    public List<User> getAllUsers() {
        try {
            return userMapper.selectList(null);
        } catch (Exception e) {
            log.error("查询所有用户失败", e);
            throw new BusinessException("查询用户列表失败");
        }
    }
    
    public User createUser(User user) {
        try {
            int result = userMapper.insert(user);
            if (result > 0) {
                log.info("用户创建成功，用户ID: {}", user.getId());
                return user;
            } else {
                throw new BusinessException("用户创建失败");
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("创建用户失败", e);
            throw new BusinessException("创建用户失败");
        }
    }
    
    public User updateUser(User user) {
        try {
            // 先检查用户是否存在
            User existingUser = userMapper.selectById(user.getId());
            if (existingUser == null) {
                return null;
            }
            
            int result = userMapper.updateById(user);
            if (result > 0) {
                log.info("用户更新成功，用户ID: {}", user.getId());
                return userMapper.selectById(user.getId());
            } else {
                throw new BusinessException("用户更新失败");
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("更新用户失败，用户ID: {}", user.getId(), e);
            throw new BusinessException("更新用户失败");
        }
    }
    
    public boolean deleteUser(Long id) {
        try {
            // 先检查用户是否存在
            User existingUser = userMapper.selectById(id);
            if (existingUser == null) {
                return false;
            }
            
            int result = userMapper.deleteById(id);
            if (result > 0) {
                log.info("用户删除成功，用户ID: {}", id);
                return true;
            } else {
                throw new BusinessException("用户删除失败");
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("删除用户失败，用户ID: {}", id, e);
            throw new BusinessException("删除用户失败");
        }
    }
}
